<template>
	<view class="main">
		<view class="top-area">
			<view class="btn" :style="{background: `linear-gradient(10deg, ${theme.primary} 30%, ${theme.primaryLight}, ${theme.primary} 70%);`}" @tap="clear">清空</view>
			<view class="btn" :style="{background: `linear-gradient(10deg, ${theme.primary} 30%, ${theme.primaryLight}, ${theme.primary} 70%);`}" @tap="preview">预览</view>
			<view class="btn" :style="{background: `linear-gradient(10deg, ${theme.primary} 30%, ${theme.primaryLight}, ${theme.primary} 70%);`}" @tap="submit">保存</view>
		</view>
		<!-- 标题 -->
		<view class="header-item">
			<textarea 
				v-show="!headerData.disabled" 
				v-model="headerData.val" 
				maxlength="50"
				auto-height="true"
				placeholder="点击输入文章标题"
				:disabled="textDisabled">
			</textarea>
			<jIcon name="icon-title" size="70"></jIcon>
		</view>
		<!-- 背景 -->
		<view class="back-cover"></view>
		<!-- 提示信息 -->
		<view v-if="list.length == 0" class="default-info">
			<jIcon name="icon-empty" size="120"></jIcon>
			<p>Tips:</p>
			<p>点击下方按钮添加自定义内容</p>
		</view>
		<drag-sort v-if="list.length != 0" :list="list" @change="change">
			<template slot-scope="{item}">
				<!-- 图片 -->
				<view v-if="item.type=='image'" class="main-item">
					<image :src="item.src" @tap="previewImage(item)" mode="aspectFit" class="left-image" style="background-color: #121212;"></image>
					<view class="edit-text" @tap="inputVal(item.mark, item.val)">
						<text v-if="!item.val" class="placeholder-text">点击输入内容</text>
						<rich-text :nodes="item.val"></rich-text>
					</view>
					<image src="@/static/icon/close.png"  @tap="closeCard(item.mark)" class="right-close"></image>
				</view>
				<!-- 文本 -->
				<view v-else-if="item.type=='text'" class="main-item">
					<view class="left-border">
						<image src="@/static/icon/text.png" class="left-image"></image>
					</view>
					<view class="edit-text" @tap="inputVal(item.mark, item.val)">
						<text v-if="!item.val" class="placeholder-text">点击输入内容</text>
						<rich-text :nodes="item.val"></rich-text>
					</view>
					<image src="@/static/icon/close.png"  @tap="closeCard(item.mark)" class="right-close"></image>
				</view>
				<!-- 视频 -->
				<view v-else-if="item.type=='video'" class="main-item">
					<video-ui :val="item" @playVideo="playVideo" @endVideo="endVideo"></video-ui>
					<view class="edit-text" @tap="inputVal(item.mark, item.val)">
						<text v-if="!item.val" class="placeholder-text">点击输入内容</text>
						<rich-text :nodes="item.val"></rich-text>
					</view>
					<image src="@/static/icon/close.png"  @tap="closeCard(item.mark)" class="right-close"></image>
				</view>
				<!-- 录音 -->
				<view v-else-if="item.type=='record'" class="main-item">
					<view class="left-border">
						<image src="@/static/icon/record.png" class="left-image"></image>
					</view>
					<view class="edit-text" @tap="inputVal(item.mark, item.val)">
						<text v-if="!item.val" class="placeholder-text">点击输入内容</text>
						<rich-text :nodes="item.val"></rich-text>
					</view>
					<image src="@/static/icon/close.png"  @tap="closeCard(item.mark)" class="right-close"></image>
				</view>
			</template>
		</drag-sort>
		<!-- 底部按钮 -->
		<add-btn
			v-bind:class="addStyle"
			:isActive="isActive"
			:Id="Id"
			@showEditor="inputVal"
			@closeCover="closeCover"
			@showCover="showCover" 
			@getImge="getImge" 
			@getVideo="getVideo" 
			@getRecord="getRecord" 
			@checkedWork="checkedWork">
		</add-btn>
	</view>
</template>

<script>
	import upload from '@/util/upload.js'
	import dragSort from '@/components/drag-sort/index.vue'
	import addBtn from '@/components/addBtn/addBtn.vue'
	import videoUi from '@/components/video-ui/video-ui.vue'
	import audioUi from '@/components/audio-ui/audio-ui.vue'
	export default {
		components:{ addBtn, dragSort, videoUi, audioUi },
		props:{
			isPreview: Boolean,
			Id: String,
			editorText: Object,
			initData: Object
		},
		watch:{
			isPreview(e){
				if(!e){
					this.headerData.disabled = false
					this.isActive = e
				}
			},
			//文本变更
			editorText(e){
				if(e.dist == 'add'){
					this.getEditor(e)
				}else if(e.dist == 'change'){
					this.saveEditor(e.html)
				}
			},
			//编辑数据初始化
			initData(e){
				if(e.isEditor){
					this.initView(e)
				}
			}
		},
		computed:{
			getDir: function(){
				let date = new Date()
				let yyyy = date.getFullYear()
				let mm = (date.getMonth() + 1)<10?`0${date.getMonth() + 1}`:`${date.getMonth() + 1}`
				return `video_${yyyy}${mm}`
			}
		},
		data() {
			return {
				theme: this.$theme,
				//标题数据
				headerData:{val:'', disabled: false},
				//自定义卡片列表数据
				list:[],
				//纯文本编辑、其他卡片编辑区分标记
				inputFlg:false,
				//当前卡片唯一标识,用于编辑后向数据列表保存数据
				editMark: '',
				//保存按钮显示标记
				isActive: false,
				//底部按钮动画样式
				addStyle:['add-button'],
				//音频作业模式
				isCheckedWork: false,
				//标题是否可编辑false可编辑 true不可编辑
				textDisabled: false
			}
		},
		methods:{
			//数据列表格式化
			initView(e){
				this.initRequest(e).then(resp=>{
					this.headerData.val = resp.result.title
					this.eassayStatus = resp.result.essayStatus
					let list = []
					resp.result.items.map((item, index)=>{
						//文字
						if(item.essayItemType == 1){
							list.push({ mark:index, type: 'text', html: item.text, val: item.text })
						}
						//图片
						else if(item.essayItemType == 2){
							list.push({ mark:index, type: 'image', src: item.imageSrc, resSrc: [item.imageSrcSource], val: item.text})
						}
						//音频
						else if(item.essayItemType == 3){
							list.push({ mark:index, type: 'record', src: item.audioSrc, resSrc: [item.audioSrcSource], duration: item.duration, val: item.text})
						}
						//视频
						else if(item.essayItemType == 4){
							list.push({ mark:index, type: 'video', src: item.videoSrc, resSrc: [item.videoSrcSource], val: item.text})
						}
					})
					this.list = list
				})
			},
			//初始化数据请求
			initRequest(e){
				return this.$http.request({
					url: 'api/Essay/GetEssay',
					method: 'GET',
					showLoading: true,
					allow: true,
					data:{
						Id: e.id,
						EssayType: e.essayType
					}
				})
			},
			//音频作业
			checkedWork(e){
				this.isCheckedWork = e
			},
			//图片预览
			previewImage(e){
				let orderIndex = this.getIndex(e.mark)
				let currentIndex = 0
				let urls = []
				this.list.map((item, index)=>{
					if(item.type == 'image'){
						if(index < orderIndex){
							currentIndex ++
						}
						urls.push(item.src)
					}
				})
				uni.previewImage({current:currentIndex, urls:urls}) 
			},
			//清空数据
			clear(){
				let that = this
				uni.showModal({
				    title: '提示',
				    content: '确认清空吗？',
				    success: function (res) {
				        if (res.confirm) {
							that.headerData.val = ''
							that.list = []
				        }
				    }
				})
			},
			//提交数据
			submit(){
				let that = this
				uni.showModal({
				    title: '提示',
				    content: '确定提交吗？',
				    success: function (res) {
				        if (res.confirm) {
							if(!that.checkItemsExists()){
								return
							}
							//数据提交
							let resp = {
								title: that.headerData,
								dtl: that.list,
								isCheckedWork: that.isCheckedWork
							}
							that.$emit('submit', resp)
				        }else{
							that.isActive = true
						}
				    }
				})
			},
			//美篇预览
			preview(){
				if(!this.checkItemsExists()){
					return
				}
				this.textDisabled = false
				this.headerData.disabled = true
				let resp = {
					title: this.headerData,
					dtl: this.list,
					isCheckedWork: this.isCheckedWork
				}
				this.$emit('preview', resp)
			},
			//编辑数据存在验证
			checkItemsExists(){
				if(!this.headerData.val){
					uni.showToast({
					    title: '请填写标题',
						icon: 'none',
					    duration: 2000
					})
					return false
				}
				if(this.list.length == 0){
					uni.showToast({
					    title: '请添加内容后再试',
						icon: 'none',
					    duration: 2000
					})
					return false
				}
				return true
			},
			//每次交换回调，数组都重新顺位
			change(e){
				this.exchangeArr(e.backData, e.data, e.frontData )
			},
			//添加照片选项卡
			getImge(e){		
				e.map((src, index)=>{
					//1：图片
					upload.upload(1, [src]).then(resp=>{
						this.list.push({ mark:this.list.length, type: 'image', src:src, val:'', resSrc: resp})
						setTimeout(()=>{
							this.commentScrollMove()
						}, 500)
					})
				})
			},
			//添加文字选项卡
			getEditor(e){
				this.list.push({ mark:this.list.length, type: 'text', html:e.html, val:e.html })
				setTimeout(()=>{
					this.commentScrollMove()
				}, 500)
			},
			//添加视频选项卡
			getVideo(e){
				//2：视频
				upload.upload(2, [e], this.getDir).then(resp=>{
					this.list.push({ mark:this.list.length, type: 'video', src:e, val:'', resSrc: resp})
					setTimeout(()=>{
						this.commentScrollMove()
					}, 500)
				})
			},
			//添加音频选项卡
			getRecord(e){
				//3：音频
				//音频作业模式
				if(this.isCheckedWork){
					if(!this.checkMoreAudio()){
						return
					}
				}
				upload.upload(3, [e.voice]).then(resp=>{
					this.list.push({ mark:this.list.length, type: 'record', src:e.voice, duration:e.duration, val: '', resSrc: resp})
					setTimeout(()=>{
						this.commentScrollMove()
					}, 500)
				})
			},
			//音频作业模式下检测多余的音频选项卡，并作提示
			checkMoreAudio(){
				let count = 0
				for(let item of this.list){
					//已经存在音频，不可以再追加音频选项卡
					if(item.type == 'record'){
						count++
					}
				}
				if(count >= 1){
					uni.showToast({
					    title: '音频作业模式下最多可录制一条音频，请删除多余的音频选项卡后再试',
						icon: 'none',
					    duration: 3000
					})
					return false
				}
				return true
			},
			//输入内容
			inputVal(e, val){
				//存在mark值则为修改卡片内容
				if(e || e==0){
					uni.navigateTo({
						url: `../editor/editor?mark=${e}&val=${val}`
					})
					this.editMark = e
				}
				//否则为新增文本卡片
				else{
					uni.navigateTo({
						url: `../editor/editor`
					})
				}
			},
			//打开文本编辑卡片, 为解决textarea无故置顶bug
			showCover(){
				this.headerData.disabled = true
			},
			//关闭文本编辑卡片
			closeCover(){
				this.inputFlg = false
				this.headerData.disabled = false
			},
			//其他卡片文本编辑保存
			saveEditor(e){
				let key = this.editMark
				for(let index in this.list){
					if(this.list[index].mark == key){
						this.list[index].val = e
					}
				}
			},
			//删除卡片
			closeCard(e){
				this.list.map((item, index)=>{
					if(item.mark == e){
						this.list.splice(index, 1)
						return
					}
				})
			},
			//卡片换位，数组数据实时更新
			exchangeArr(val1, val2, val3){
				//x<=>0
				if(!val3){
					let index1 = this.getIndex(val1.mark)
					let index2 = this.getIndex(val2.mark)
					//删除后再插入
					let temp = this.list[index2]
					this.list.splice(index2, 1)
					this.list.splice(0, 0, temp)
				}
				//x<=>max
				else if(!val1){
					let index2 = this.getIndex(val2.mark)
					let index3 = this.getIndex(val3.mark)	
					//删除再追加当前元素
					let temp = this.list[index2]
					this.list.splice(index2, 1)
					this.list.push(temp)
				}
				//x<=>x
				else{
					let index1 = this.getIndex(val1.mark)
					let index2 = this.getIndex(val2.mark)
					let index3 = this.getIndex(val3.mark)
					//up=>down特殊处理
					if(index2 < index1 && index2 < index3){
						// 选择卡片删除后再插入到后面
						let temp = this.list[index2]
						this.list.splice(index2, 1)
						this.list.splice(index3, 0, temp)
					}
					//down=>up
					else{
						// 选择卡片删除后再插入到前面
						let temp = this.list[index2]
						this.list.splice(index2, 1)
						this.list.splice(index1, 0, temp)
					}					
				}				
			},
			//通过mark标记实时获取当前元素在数组中位置
			getIndex(mark){
				for(let index in this.list){
					if(this.list[index].mark == mark){
						return index
						break
					}
				}
			},
			//视频播放
			async playVideo(){
				this.headerData.disabled = true
			},
			//视频停止播放
			endVideo(){
				this.headerData.disabled = false
			},
			//追加卡片后页面滚动
			commentScrollMove(){
				uni.pageScrollTo({
				    scrollTop: 99999999999
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.main{
		margin: 0;
		width: 100vw;
		flex-direction: column;
		justify-content: flex-start;
		align-items: center;
		.top-area{
			width: 100%;
			display: flex;
			justify-content: space-between;
			align-items: center;
			font-size: 30rpx;
			.btn{
				margin: 10rpx;
				width: 100rpx;
				padding: 10rpx;
				border-radius: 10rpx;
				font-size: 26rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				color: #fff;
			}
		}
		.back-cover{
			width: 100vw;
			height: 100vh;
			background-color: #f3f3f3;
			opacity: 0.8;
			position: fixed;
			top: 0;
			left: 0;
			z-index: -1;
		}
		.option-cover{
			width: 100vw;
			height: 100vh;
			position: fixed;
			left: 0;
			top: 0;
			background-color: #353535;
			opacity: 0.2;
		}
		.cancel-button{
			position: fixed;
			width: 120rpx;
			height: 120rpx;
			border-radius: 50%;
			left: 18%;
			top: 40%;
			background-color: #d4237a;
			color: #fff;
			font-size: 35rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			transition: 0.3s;
		}
		.save-button{
			position: fixed;
			width: 120rpx;
			height: 120rpx;
			border-radius: 50%;
			left: 43%;
			top: 40%;
			background-color: #67C23A;
			color: #fff;
			font-size: 35rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			transition: 0.3s;
		}
		.preview-button{
			position: fixed;
			width: 120rpx;
			height: 120rpx;
			border-radius: 50%;
			left: 68%;
			top: 40%;
			background-color: #efb336;
			color: #fff;
			font-size: 35rpx;
			display: flex;
			justify-content: center;
			align-items: center;
			transition: 0.3s;
		}
		.preview-button:active,
		.cancel-button:active,
		.save-button:active{
			transform: scale(1.2);
			opacity: 0.8;
		}
		.show{
			animation: 0.5s show-save;
		}
		.hide{
			animation: 0.3s hide-save;
		}
		@keyframes add-shock{
			0%{
				transform: scale(1.2);
			}
			25%{
				transform: scale(0.9);
			}
			50%{
				transform: scale(1.2);
			}
			75%{
				transform: scale(0.9);
			}
			100%{
				transform: scale(1.0);
			}
		}
		@keyframes show-save{
			0%{
				width: 10rpx;
				height: 10rpx;
				left: 50%;
				transform: translateY(100vh);
			}
			100%{
				transform: translateY(0);
			}
		}
		@keyframes hide-save{
			0%{
				transform: translateY(0);
			}
			100%{
				font-size: 0;
				width: 10rpx;
				height: 10rpx;
				left: 50%;
				transform: translateY(100vh);
			}
		}
		.add-button{
			position: fixed;
			bottom: -75rpx;
			z-index: 999;
		}
		.shock{
			animation: 0.6s add-shock;
		}
		.header-item{
			box-shadow: 0 0 8rpx 2rpx #efeef1;
			padding: 10rpx;
			margin: 10rpx 0 30rpx 0;
			background-color: #fff;
			position: relative;
			display: flex;
			align-items: center;
			height: 100rpx;
			textarea{
				width: 85%;
				max-height: 80rpx;
				padding: 15rpx;
				letter-spacing: 10rpx;
				font-size: 30rpx;
			}
		}
		.default-info{
			position: fixed;
			top: 10vh;
			width: 100vw;
			height: 70vh;
			font-size: 30rpx;
			color: #818181;
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;
		}
		.main-item{
			display: flex;
			justify-content: flex-start;
			align-items: center;
			position: relative;
			font-size: 30rpx;
			padding-left: 10rpx;
			height: 250rpx;
			.left-image{
				width: 250rpx;
				height: 220rpx;
			}
			.edit-text{
				position: relative;
				width: 400rpx;
				height: 210rpx;
				padding: 5rpx 15rpx 5rpx 15rpx;
				border-radius: 10rpx;
				word-wrap: break-word;
				word-break: break-all;
				overflow-x: hidden;
				.placeholder-text{
					color: #878787;
					font-size: 30rpx;
				}
			}
			.right-close{
				position: absolute;
				left: 8rpx;
				top: 12rpx;
				width: 60rpx;
				height: 60rpx;
				transform: rotate(180deg);
			}
			.rich-text{
				width: 400rpx;
				padding: 15rpx;
			}
		}
	}
</style>
